/**
 * Copyright (C) 2017 ilikeshatang. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wetao.trackscreendemo.voicerecorder;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.PowerManager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.wetao.trackscreendemo.FileUtils;

import cn.forward.androids.utils.LogUtil;


/**
 * desc:   Voice recorder view
 * author: wangshanhai
 * email: ilikeshatang@gmail.com
 * date: 2017/10/31 15:27
 */
public class VoiceRecorderView extends RelativeLayout{
    public static final int HANDLER_VOLUME = 1;
    protected Context context;
    protected boolean is120Miao = false;
    protected int m120Miao = 120;
    protected VoiceRecorder voiceRecorder;

    protected PowerManager.WakeLock wakeLock;

    protected String release_to_cancel = "";
    protected String move_up_to_cancel = "";

    protected EaseVoiceRecorderCallback mRecorderCallback;

    protected Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // change image
            if(msg.what == HANDLER_VOLUME) {
                onSetVolume(msg.arg1, msg.arg2);
            }
        }
    };

    public VoiceRecorderView(Context context) {
        super(context);
        init(context);
    }

    public VoiceRecorderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public VoiceRecorderView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public void init(Context context) {
        this.context = context;
        voiceRecorder = new VoiceRecorder(micImageHandler);
        wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "voice");
    }

    /**
     * on speak button touched
     *
     * @param v
     * @param event
     */
    public boolean onPressToSpeakBtnTouch(View v, MotionEvent event, EaseVoiceRecorderCallback recorderCallback) {
        mRecorderCallback = recorderCallback;
        int actionMasked = event.getActionMasked();
        int action = event.getAction();
        int actionIndex = event.getActionIndex();
        int pointCount = event.getPointerCount();
        /*Logger.i("手指点击： action = " + action
                + ", actionMasked = " + actionMasked
                + ", actionIndex = " + actionIndex
                + ", pointCount = " + pointCount
        );*/
        switch (event.getAction()) {
            case MotionEvent.ACTION_POINTER_DOWN:{
                //Logger.i("手指按下多点");
                return true;
            }
            case MotionEvent.ACTION_POINTER_UP:{
                //Logger.i("手指弹起多点");
                if (actionIndex != 0) {
                    return true;
                }
                v.setPressed(false);
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    discardRecording();
                } else {
                    // stop recording and send voice file
                    stopRecordUpOr120Miao();
                }
                return true;
            }
            case MotionEvent.ACTION_DOWN: {
                if (actionIndex != 0) {
                    return true;
                }
                //Logger.i("手指按下单点");
                is120Miao = false;
                try {
                    /**
                     * 该处展示不处理
                     */
                  /*  if (VoicePlayClickListener.isPlaying)
                        VoicePlayClickListener.currentPlayListener.stopPlayVoice();*/
                    v.setPressed(true);
                    startRecording();
                } catch (Exception e) {
                    v.setPressed(false);
                }
                return true;
            }
            case MotionEvent.ACTION_MOVE: {
                if (actionIndex != 0) {
                    return true;
                }
                //Logger.i("手指移动");
                if (event.getY() < 0) {
                    showReleaseToCancelHint();
                } else {
                    showMoveUpToCancelHint();
                }
                return true;
            }
            case MotionEvent.ACTION_UP: {
                if (actionIndex != 0) {
                    return true;
                }
                //Logger.i("手指弹起单点");
                v.setPressed(false);
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    discardRecording();
                } else {
                    // stop recording and send voice file
                    stopRecordUpOr120Miao();
                }
                return true;
            }
            default: {
                if (actionIndex != 0) {
                    return true;
                }
                discardRecording();
                return false;
            }
        }
    }

    private void stopRecordUpOr120Miao() {
        if(is120Miao) {
            return;
        }
        try {
            int length = stopRecoding();
            if (length > 0) {
                onVoiceRecordComplete(getVoiceFilePath(), length);
            } else if (length == EMError.FILE_INVALID) {
                onVoiceRecordFail();
                LogUtil.e("没有录音权限，录音失败");
            } else {
                onVoiceRecordFail();
                LogUtil.e("录音时间太短，录音失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // Toast.makeText(context, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
        }
    }

    public interface EaseVoiceRecorderCallback {
        /**
         * on voice record complete
         *
         * @param voiceFilePath   录音完毕后的文件路径
         * @param voiceTimeLength 录音时长
         */
        void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength);
        void onVoiceStartRecording(String trip);
        void onVoiceMoveRecording(String trip);
        void onVoiceRecordFail();
        void onSetVolume(int volume, int second);
    }

    private void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
        if (mRecorderCallback != null) {
            mRecorderCallback.onVoiceRecordComplete(voiceFilePath, voiceTimeLength);
        }
    }
    private void onVoiceStartRecording(String trip) {
        if (mRecorderCallback != null) {
            mRecorderCallback.onVoiceStartRecording(trip);
        }
    }
    private void onVoiceMoveRecording(String trip) {
        if (mRecorderCallback != null) {
            mRecorderCallback.onVoiceMoveRecording(trip);
        }
    }

    private void onVoiceRecordFail() {
        if (mRecorderCallback != null) {
            mRecorderCallback.onVoiceRecordFail();
        }
    }
    private void onSetVolume(int volume, int second) {
        if (mRecorderCallback != null) {
            mRecorderCallback.onSetVolume(volume, second);
            if(second >= m120Miao) {
                stopRecordUpOr120Miao();
                is120Miao = true;
            }
        }
    }

    public void startRecording() {
        if (!FileUtils.isSdcardExist()) {
            LogUtil.e( "SD卡不存在");
            return;
        }
        try {
            wakeLock.acquire();
            voiceRecorder.startRecording(context);
            onVoiceStartRecording("松开结束");
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
            onVoiceRecordFail();
            LogUtil.e("录音失败");
            return;
        }
    }

    public void showReleaseToCancelHint() {
        onVoiceMoveRecording("上滑取消");
    }

    public void showMoveUpToCancelHint() {
        onVoiceMoveRecording("松开结束");
    }

    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_START
                    || voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_PAUSE) {
                voiceRecorder.discardRecording();
                onVoiceRecordFail();
            }
        } catch (Exception e) {
        }
    }

    public int stopRecoding() {
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }


    /**
     * 目前需要传入15张帧动画png
     *
     * @param animationDrawable
     */
    public void setDrawableAnimation(Drawable[] animationDrawable) {
    }


    /**
     * 设置按下显示的提示
     *
     * @param releaseToCancelHint
     */
    public void setShowReleaseToCancelHint(String releaseToCancelHint) {
        this.release_to_cancel = releaseToCancelHint;
    }

    /**
     * 设置手指向上移动显示的提示语
     *
     * @param moveUpToCancelHint
     */
    public void setShowMoveUpToCancelHint(String moveUpToCancelHint) {
        this.move_up_to_cancel = moveUpToCancelHint;
    }

    public void set120Miao(int miao) {
        m120Miao = miao;
    }

    public void setVoiceFilePath(String voiceFilePath) {
        voiceRecorder.setVoiceFilePath(voiceFilePath);
    }

}
